package com.cat.binaryTree;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/rotate-list/
 * @create 2025/9/26 20:30
 * @since JDK17
 */

public class Solution68 {
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null) {
            return head;
        }
        int n = 0;
        ListNode cur, slow, fast;
        for (cur = head; cur != null; n++, cur = cur.next);
        k %= n;
        if (k == 0) {
            return head;
        }
        slow = fast = head;
        for (int i = 0; i < k; i++) {
            fast = fast.next;
        }
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        cur = slow.next;
        slow.next = null;
        fast.next = head;
        return cur;
    }
}
